import os
import sys
import traceback

from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QApplication, QMessageBox, QMainWindow
from uiimpl.compareimpl import CompareImpl
from uiimpl.testimpl import TestImpl
from common.initpath import init_excel_dir
from uidemo.ui_server import UiServer


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 页签管理
        self.main_layout = None
        self.tabWidget = None

        # 初始化界面
        self.init_ui()

        # 初始化数据
        # self.init_data()

        # 引用的页签
        self.tab_compare = None  # 配置对比
        self.tab_test = None  # test
        self.tab_server = None  # 服务器

    def init_data(self):
        init_excel_dir()
        pass

    def init_ui(self):
        # 获取当前脚本所在目录
        base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
        icon_path = os.path.join(base_path, 'tools.ico')
        self.setWindowTitle("Tools")
        self.resize(720, 480)
        self.setWindowIcon(QIcon(icon_path))
        self.center()

        # 页签管理
        self.main_layout = QtWidgets.QVBoxLayout()
        self.setLayout(self.main_layout)
        self.tabWidget = QtWidgets.QTabWidget()
        self.tabWidget.setObjectName("tabWidget")
        self.main_layout.addWidget(self.tabWidget)
        self.setCentralWidget(self.tabWidget)

        self.tab_compare = CompareImpl()
        self.tab_test = TestImpl()
        self.tab_server = UiServer()

        self.tabWidget.addTab(self.tab_compare, '配置对比')
        self.tabWidget.addTab(self.tab_server, '服务器')
        self.tabWidget.addTab(self.tab_test, 'test')

    # 设置窗口居中
    def center(self):
        qr = self.frameGeometry()
        cp = self.screen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    # # 如果未限制最大长宽，可以自适应移动控件
    # def resizeEvent(self, a0: QtGui.QResizeEvent):
    #     size = a0.size()
    #     self.tabWidget.setFixedSize(size.width(), size.height())


def excepthook(exc_type, exc_value, exc_traceback):
    """全局异常捕获"""
    error_msg = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
    print(f"捕获到未处理的异常：\n{error_msg}")
    QMessageBox.critical(None, "未处理的异常", f"程序发生未处理的异常：\n{error_msg}")


if __name__ == "__main__":
    # 设置全局异常捕获
    sys.excepthook = excepthook

    # 创建应用和主窗口
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    # 运行应用
    sys.exit(app.exec())
